Warning: file_put_contents(aCache/aDaily/post/opendatascience/--): Failed to open stream: No space left on device in /var/www/tg-me/post.php on line 50
Data Science by ODS.ai 🦜 | Telegram Webview: opendatascience/2273 -
Telegram Group & Telegram Channel
Forwarded from Python/ django
🖥 Новинка в Python 3.14: t-строки — типобезопасные f-строки

Python 3.14 вводит t"..." — новый синтаксис для строк, ориентированных на безопасность типов и интеграцию с системами шаблонов, SQL, HTML и др.

🔹 Что такое t-строка?
t"..." — это как f"...", но:

- интерполяция ограничена и контролируема;
- поддерживается строгое соответствие шаблону;
- можно передавать переменные явно, предотвращая SQL-инъекции и XSS.

🔸 Пример:

name = "Alice"
greeting = t"Hello, {name}!" # t-строка
Вместо немедленной подстановки, как в f"...", t"..." создает шаблон с выражениями как параметрами.


🔐 Зачем это нужно?
Безопасность при генерации SQL, HTML, JSON

Улучшение инструментов и проверки типов (через static analysis)

Контроль над контекстом исполнения (больше нельзя просто вставить переменную как есть — нужно передать её явно)

📦 Использование:
t-строки — это первый шаг к "template string literals" как в TypeScript.

Можно использовать с функциями:


def html(template: T[str]) -> SafeHTML:
...

html(t"<div>{user_input}</div>")


💡 Почему это важно?
Старый код:


f"SELECT * FROM users WHERE name = '{user_name}'"
может привести к SQL-инъекциям и XSS.
t-строки — безопасная альтернатива с встроенной защитой.


🛡 Пример: безопасный HTML

template = t"<p>{user_input}</p>"
html_output = html(template)
# <p>&lt;script&gt;alert('bad')&lt;/script&gt;</p>

Функция html() может вернуть не просто строку, а полноценный HTMLElement.
Больше никакой "грязи" — всё чисто и типобезопасно.

🔍 Работа с шаблоном
t-строки позволяют получить доступ к содержимому:


template = t"Hello {name}!"
template.strings # ("Hello ", "!")
template.values # (name,)
template.interpolations[0].format_spec # ">8"

Можно и вручную собрать шаблон:


Template("Hello ", Interpolation(value="World", expression="name"), "!")


🚀 Вывод:
t"..." — шаг к безопасным шаблонам и типизации строк в Python.
Готовься к будущему Python — безопасному по умолчанию.

📌 Подробнее здесь

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/opendatascience/2273
Create:
Last Update:

🖥 Новинка в Python 3.14: t-строки — типобезопасные f-строки

Python 3.14 вводит t"..." — новый синтаксис для строк, ориентированных на безопасность типов и интеграцию с системами шаблонов, SQL, HTML и др.

🔹 Что такое t-строка?
t"..." — это как f"...", но:

- интерполяция ограничена и контролируема;
- поддерживается строгое соответствие шаблону;
- можно передавать переменные явно, предотвращая SQL-инъекции и XSS.

🔸 Пример:


name = "Alice"
greeting = t"Hello, {name}!" # t-строка
Вместо немедленной подстановки, как в f"...", t"..." создает шаблон с выражениями как параметрами.


🔐 Зачем это нужно?
Безопасность при генерации SQL, HTML, JSON

Улучшение инструментов и проверки типов (через static analysis)

Контроль над контекстом исполнения (больше нельзя просто вставить переменную как есть — нужно передать её явно)

📦 Использование:
t-строки — это первый шаг к "template string literals" как в TypeScript.

Можно использовать с функциями:


def html(template: T[str]) -> SafeHTML:
...

html(t"<div>{user_input}</div>")


💡 Почему это важно?
Старый код:


f"SELECT * FROM users WHERE name = '{user_name}'"
может привести к SQL-инъекциям и XSS.
t-строки — безопасная альтернатива с встроенной защитой.


🛡 Пример: безопасный HTML

template = t"<p>{user_input}</p>"
html_output = html(template)
# <p>&lt;script&gt;alert('bad')&lt;/script&gt;</p>

Функция html() может вернуть не просто строку, а полноценный HTMLElement.
Больше никакой "грязи" — всё чисто и типобезопасно.

🔍 Работа с шаблоном
t-строки позволяют получить доступ к содержимому:


template = t"Hello {name}!"
template.strings # ("Hello ", "!")
template.values # (name,)
template.interpolations[0].format_spec # ">8"

Можно и вручную собрать шаблон:


Template("Hello ", Interpolation(value="World", expression="name"), "!")


🚀 Вывод:
t"..." — шаг к безопасным шаблонам и типизации строк в Python.
Готовься к будущему Python — безопасному по умолчанию.

📌 Подробнее здесь

@pythonl

BY Data Science by ODS.ai 🦜




Share with your friend now:
tg-me.com/opendatascience/2273

View MORE
Open in Telegram


Data Science by ODS ai 🦜 Telegram | DID YOU KNOW?

Date: |

Should You Buy Bitcoin?

In general, many financial experts support their clients’ desire to buy cryptocurrency, but they don’t recommend it unless clients express interest. “The biggest concern for us is if someone wants to invest in crypto and the investment they choose doesn’t do well, and then all of a sudden they can’t send their kids to college,” says Ian Harvey, a certified financial planner (CFP) in New York City. “Then it wasn’t worth the risk.” The speculative nature of cryptocurrency leads some planners to recommend it for clients’ “side” investments. “Some call it a Vegas account,” says Scott Hammel, a CFP in Dallas. “Let’s keep this away from our real long-term perspective, make sure it doesn’t become too large a portion of your portfolio.” In a very real sense, Bitcoin is like a single stock, and advisors wouldn’t recommend putting a sizable part of your portfolio into any one company. At most, planners suggest putting no more than 1% to 10% into Bitcoin if you’re passionate about it. “If it was one stock, you would never allocate any significant portion of your portfolio to it,” Hammel says.

That growth environment will include rising inflation and interest rates. Those upward shifts naturally accompany healthy growth periods as the demand for resources, products and services rise. Importantly, the Federal Reserve has laid out the rationale for not interfering with that natural growth transition.It's not exactly a fad, but there is a widespread willingness to pay up for a growth story. Classic fundamental analysis takes a back seat. Even negative earnings are ignored. In fact, positive earnings seem to be a limiting measure, producing the question, "Is that all you've got?" The preference is a vision of untold riches when the exciting story plays out as expected.

Data Science by ODS ai 🦜 from no


Telegram Data Science by ODS.ai 🦜
FROM USA